package com.java.tutorials.concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier的例子
 *
 * @author Jun Yang
 */
public class BarDemo {

    public static void main(String[] args) {
        CyclicBarrier cbar = new CyclicBarrier(3, new BarAction());

        System.out.println("Starting");

        new MyThread(cbar, "A");
        new MyThread(cbar, "B");
        new MyThread(cbar, "C");
        new MyThread(cbar, "X");
        new MyThread(cbar, "Y");
        new MyThread(cbar, "Z");
    }


    static class MyThread implements Runnable {
        CyclicBarrier cbar;
        String name;

        MyThread(CyclicBarrier c, String n) {
            cbar = c;
            name = n;
            new Thread(this).start();
        }

        @Override
        public void run() {
            System.out.println(name);

            try {
                cbar.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    static class BarAction implements Runnable {
        @Override
        public void run() {
            System.out.println("Barrier Reached!");
        }
    }
}


